package com.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * N皇后
 */
public class No51 {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> result = new ArrayList<>();
        int[] chess = new int[n];
        solve(0, chess, result);
        return result;
    }

    private void solve(int index, int[] chess, List<List<String>> result) {
        if (index == chess.length) {
            List<String> list = new ArrayList<>();
            for (int i = 0; i < chess.length; i++) {
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < chess.length; j++) {
                    if (j == chess[i]) {
                        sb.append('Q');
                    } else {
                        sb.append('.');
                    }
                }
                list.add(sb.toString());
            }
            result.add(list);
            return;
        }
        for (int i = 0; i < chess.length; i++) {
            chess[index] = i;
            if (judge(index, chess)) {
                solve(index + 1, chess, result);
            }
        }
    }

    private boolean judge(int index, int[] chess) {
        for (int i = 0; i < index; i++) {
            if (chess[i] == chess[index] || Math.abs(chess[index] - chess[i]) == Math.abs(index - i)) {
                return false;
            }
        }
        return true;
    }
}
